package com.gzhryc.shared_device.oem.micro.api.controllers.callback;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.time.DateUtils;

import com.gzhryc.common.logging.Logger;
import com.gzhryc.pay.adaptation.weixin.DefaultWXPayConfig;
import com.gzhryc.pay.adaptation.weixin.WXPayUtils;
import com.gzhryc.pay.adaptation.weixin.msg.WXPayNotify;
import com.gzhryc.pay.adaptation.weixin.msg.WXPayNotifyResponse;
import com.gzhryc.pay.adaptation.weixin.msg.normal.WXPayNormalPayNotify;
import com.gzhryc.pay.adaptation.weixin.msg.normal.WXPayNormalRefundNotify;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.common.payment.dao.db.WXRefundOrder;
import com.gzhryc.shared_device.common.payment.services.WXRefundOrderService;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.member.services.MemberRechargeOrderService;
import com.gzhryc.shared_device.oem.micro.api.MicroConstants;
import com.gzhryc.shared_device.oem.micro.api.OrderCollectManager;

public class WXPayRechargeCallbackController {

    static Logger log = Logger.getLogger(WXPayRechargeCallbackController.class);

    @Route(value = {"/paycall/wxpay/{appId}/recharge/pay","/paycall/recharge/wxpay/{appId}/pay"})
    public WXPayNotifyResponse rechargePay(HttpServletRequest request, HttpServletResponse response) {
        String appId = WebUtils.getString(request, "appId");
        WXPayNotify notify = null;
        try {
            notify = WebUtils.getJsonRequest(request, WXPayNotify.class);
            log.info("{{0}}微信普通支付回调(充值支付)，回调内容：{{1:json}}", appId, notify);
            DefaultWXPayConfig config = PayServiceFactory.self().getWXPayConfig(appId, EBusinessType.RECHARGE.index());
            if (config != null && notify != null) {
                WXPayNormalPayNotify payNotify = WXPayUtils.getWXPayNormalPayNotify(notify, config);
                OperateInfo operateInfo = new OperateInfo(MicroConstants.PROGRAM_TYPE, MicroConstants.PROGRAM_TYPE_NAME);
                operateInfo.setOperator(EOperatorType.System.index(),"微信充值回调接口");
                operateInfo.setOperateNote("微信支付充值回调");
                OrderCollectManager.payResult(payNotify, operateInfo);
            } else {
                log.error("未获取{{0}}的微信配置或空回调信息", appId);
            }
        } catch (Exception e) {
            log.error(appId + "微信支付回调错误，" + e.getMessage(), e);
        }
        return new WXPayNotifyResponse();
    }

    @Route(value = {"/paycall/wxpay/{appId}/recharge/refund","/paycall/recharge/wxpay/{appId}/refund"})
    public WXPayNotifyResponse rechargeRefund(HttpServletRequest request, HttpServletResponse response) {
        String appId = WebUtils.getString(request, "appId");
        WXPayNotify notify = null;
        try {
            notify = WebUtils.getJsonRequest(request, WXPayNotify.class);
            log.info("{{0}}微信普通退款回调(充值退款)，回调内容：{{1:json}}", appId, notify);
            DefaultWXPayConfig config = PayServiceFactory.self().getWXPayConfig(appId, EBusinessType.RECHARGE.index());
            if (notify != null && config != null) {
                WXPayNormalRefundNotify refundNotify = WXPayUtils.getWXPayNormalRefundNotify(notify, config);
                //TODO 需要查询上一年订单
                Date currentDate = new Date();
                WXRefundOrder refundOrder = WXRefundOrderService.self(currentDate).refundResult(refundNotify);
                if(refundOrder == null){
                    //查询上一年订单
                    currentDate = DateUtils.addYears(currentDate,-1);
                    refundOrder = WXRefundOrderService.self(currentDate).refundResult(refundNotify);
                }
                if (refundOrder != null) {
                    OperateInfo operateInfo = new OperateInfo(MicroConstants.PROGRAM_TYPE, MicroConstants.PROGRAM_TYPE_NAME);
                    operateInfo.setOperator(EOperatorType.System.index(),"微信充值退款接口");
                    operateInfo.setOperateNote("微信充值退款回调");
                    //处理
                    MemberRechargeOrderService.self(refundOrder.getCreateDate()).refundResult(refundOrder, operateInfo);
                } else {
                    log.error("微信普通退款回调未找到退款订单，回调内容：{{0:json}}", notify);
                }
            } else {
                log.error("未获取{{0}}的微信配置或空回调信息", appId);
            }
        } catch (Exception e) {
            log.error(appId + "微信退款回调错误，" + e.getMessage(), e);
        }
        return new WXPayNotifyResponse();
    }
}
